﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WP_Client
{
    public class Common
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <returns></returns>
        public static string DeserializeObject<T>(T t)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(t.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, t);
                byte[] tempAry = stream.ToArray();
                return Encoding.UTF8.GetString(tempAry, 0, tempAry.Length);
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        public static T DeserializeJson<T>(string json)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        public static T DeserializeJson<T>(Byte[] byteArray)
        {
            string str = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str.Replace("\0", ""))))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }
}
